using System;
using System.Collections.Generic;
using BuildMonitor.Properties;
using Microsoft.TeamFoundation.Build.Client;
using System.Diagnostics;
using Amplify.Twitter;

namespace BuildMonitor.Engine
{
	public class TwitterBuildPublisherHelper : IBuildPublisher
	{
		private ConsoleText consoleText;

		public TwitterBuildPublisherHelper(ConsoleText consoleText)
		{
			this.consoleText = consoleText;
		}

		~TwitterBuildPublisherHelper()
		{
			Dispose(false);
		}

		public void Dispose()
		{
			Dispose(true);
		}

		protected void Dispose(bool disposing)
		{
			if (disposing)
			{
				Close();
				client = null;
				GC.SuppressFinalize(this);
			}
		}

		private StatusClient client;

		public void Init(List<BuildStoreEvent> events)
		{
			Twitter.SetCredentials(Settings.Default.TwitterAccount, Settings.Default.TwitterPassword);
			client = Twitter.CreateStatusClient();
		}

		public void BuildCompletionEvent(BuildStoreEvent buildStoreEvent)
		{
			consoleText.WriteLine("Build Completion Event");
			var status = buildStoreEvent.Data.Status;
			if (status.Equals(BuildStatus.Succeeded))
				client.Create("Yay! I got built successfully again!");
			if (status.Equals(BuildStatus.Failed))
				client.Create(string.Format("Oops!! {0} broke me. Go find them and beat them up!", buildStoreEvent.Data.RequestedBy));
			if (status.Equals(BuildStatus.PartiallySucceeded))
				client.Create(string.Format("Hmm... Something's not quite right.  Can you get {0} to have a look?", buildStoreEvent.Data.RequestedBy));
			if (status.Equals(BuildStatus.Stopped))
				client.Create(string.Format("I was building and then {0} asked me to stop.  Hmppf.", buildStoreEvent.Data.RequestedBy));
		}

		public void BuildStatusChangeEvent(BuildStoreEvent buildStoreEvent)
		{
			consoleText.WriteLine("Build Status Event");
			client.Create(String.Format("{0} changed my build quality to {1}", buildStoreEvent.Data.LastChangedBy, buildStoreEvent.Data.Quality));
		}

		public void Close()
		{
			client.Create("I'm being turned off :-(");
		}
	}
}